<template>
  <div class="app-container workflow">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane :label="$t('ccworkflow.tab1')" name="second">
        <workfence ref="workFlow" :map-list="mapList" />
      </el-tab-pane>
      <el-tab-pane :label="$t('ccworkflow.tab2')" name="first">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <span style="float: left">{{ $t("area.Layer") }}:</span>
            <treeselect
              v-model="mapId"
              :placeholder="$t('area.chosenLayer')"
              :max-height="300"
              :options="mapList"
              style="float: left; width: 200px"
              @input="nodeClick"
            />
            <span
              style="margin-left: 20px"
            >{{ $t('ccworkflow.flow') }}:</span>
          </el-col>
          <el-col :span="1.5">
            <el-select
              v-model="workFlowType"
              filterable
              :placeholder="$t('operating.pleaseChosen')"
              @change="queryWorkFlow()"
            >
              <el-option
                v-for="item in $t('ccworkflow.optionList')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <!-- <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="queryWorkFlow"
            >{{ $t("operating.search") }}</el-button> -->
            <span
              style="margin-left: 20px"
            >{{ $t("operating.operating") }}:</span>
          </el-col>

          <el-col :span="1.5">
            <el-tooltip
              v-for="(item, index) in $t('fence.drawSelectForms')"
              :key="index"
              effect="dark"
              :content="item.label"
              placement="bottom"
            >
              <el-button
                :key="item.value"
                type="text"
                :autofocus="false"
                :data-id="item.value"
                :label="item.label"
                :disabled="disabled"
                size="mini"
                @click="handleChange(index, item.value)"
              >
                <i
                  :class="[
                    item.id == colorFlag ? item.unIconFont : item.iconFont,
                  ]"
                />
              </el-button>
            </el-tooltip>

          </el-col>

          <!-- <el-col :span="1.5">
            <div class="positiondiv">
              <span />
            </div>
          </el-col>
          <el-col :span="1.5">
            <div class="scalediv">
              <span />
            </div>
          </el-col> -->
        </el-row>

        <div class="map-container">
          <div id="map" />
        </div>
        <div id="market" class="market" />

        <el-drawer
          custom-class="changeDialog"
          :title="$t('fence.fenceSet')"
          :visible.sync="fenceEditVisible"
          direction="rtl"
          :modal-append-to-body="true"
          size="100%"
          :modal="false"
          @open="disabled = true"
          @close="closeDialog"
        >
          <el-tabs :tab-position="'top'" style="width: 500px; margin: 0 15px">
            <el-tab-pane label="流程作业">
              <el-form
                ref="form"
                :rules="rules"
                :model="form"
              >
                <el-form-item :label="$t('fence.type')">
                  <el-input v-model="form.fenceName" disabled width="50%" />
                </el-form-item>
                <el-form-item :label="$t('ccworkflow.orderNum')" prop="type">
                  <el-select v-model="form.type" disabled placeholder="请选择">
                    <el-option label="作业流程" value="1" />
                    <el-option label="路测流程" value="2" />
                  </el-select>
                </el-form-item>

                <el-form-item :label="$t('ccworkflow.orderNum')" prop="orderNum">
                  <el-input-number
                    v-model="form.orderNum"
                    controls-position="right"
                    :min="1"
                    :max="10"
                  />
                </el-form-item>
                <el-form-item :label="$t('ccworkflow.operationId')" prop="operationId">
                  <el-input v-model="form.operationId" />
                </el-form-item>
                <el-form-item :label="$t('ccworkflow.operationName')" prop="operationName">
                  <el-input v-model="form.operationName" />
                </el-form-item>
                <el-form-item :label="$t('ccworkflow.maxDuration')" prop="maxDuration">
                  <el-input v-model="form.maxDuration" />
                </el-form-item>
                <el-form-item :label="$t('ccworkflow.minDuration')" prop="minDuration">
                  <el-input v-model="form.minDuration" />
                </el-form-item>
                <el-form-item :label="$t('ccworkflow.intoCount')" prop="intoCount">
                  <el-input v-model="form.intoCount" />
                </el-form-item>
                <el-form-item :label="$t('ccworkflow.remark')" prop="remark">
                  <el-input v-model="form.remark" />
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="submitForm('form')"
                  >{{ $t("common.cmodify") }}</el-button>
                  <!-- <el-button @click="resetForm('form')">重置</el-button> -->
                </el-form-item>
              </el-form>

              <div v-if="formArrList.length > 0" class="fenceTemp">
                <el-table :data="formArrList">
                  <el-table-column property="fenceName" label="围栏名" />
                  <el-table-column property="fenceId" label="围栏ID" />
                  <!-- <el-table-column property="type" label="流程" /> -->
                  <el-table-column :label="$t('ccworkflow.maxDuration')">
                    <template slot-scope="scope">{{ scope.row.type|formatType(scope.row.type) }}</template>
                  </el-table-column>
                  <el-table-column property="orderNum" :label="$t('ccworkflow.orderNum')" />
                  <el-table-column property="intoCount" :label="$t('ccworkflow.intoCount')" />
                  <el-table-column property="maxDuration" :label="$t('ccworkflow.maxDuration')" />
                  <el-table-column property="minDuration" :label="$t('ccworkflow.minDuration')" />
                  <el-table-column :label="$t('common.coperate')" width="100">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        size="small"
                        @click="fenceTempDel(scope.row, scope.$index)"
                      >{{ $t("common.cdelete") }}</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <div v-if="formArrList.length > 0">
                <el-button @click="cancelflow()">{{ $t("common.ccancel") }}</el-button>
                <el-button
                  type="primary"
                  @click="saveTempFence()"
                >{{ "common.csave" }}</el-button>
              </div>
            </el-tab-pane>

            <!-- <el-tab-pane label="围栏信息">
              <div style="padding: 0 20px">
                <el-form label-width="80px">
                  <el-form-item :label="$t('fence.fenceName')">
                    <el-input v-model="fenceName" />
                  </el-form-item>
                  <el-form-item :label="$t('fence.fenceType')">
                    <el-select
                      v-model="fenceType"
                      :multiple="true"
                      filterable
                      :placeholder="$t('operating.pleaseChosen')"
                    >
                      <el-option
                        v-for="item in $t('fence.fenceTypeList')"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item :label="$t('realtime.styleModification')">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="$t('realtime.changeFenceStyle')"
                      placement="top"
                    >
                      <el-color-picker
                        v-model="color1"
                        show-alpha
                        size="mini"
                        @change="changeColor()"
                      />
                    </el-tooltip>
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="$t('realtime.modifyBorderStyle')"
                      placement="top"
                      style="margin-left: 10px"
                    >
                      <el-color-picker
                        v-model="color2"
                        show-alpha
                        size="mini"
                        @change="changeColor()"
                      />
                    </el-tooltip>
                  </el-form-item>

                  <span v-if="arr.length > 0">
                    <el-form-item
                      v-for="(item, i) in allDataCount"
                      :key="i"
                      :label="i.toString()"
                    >
                      <el-row>
                        <el-col :span="12">
                          <el-form label-width="20px" @submit.native.prevent>
                            <el-form-item label="X:">
                              <el-input-number
                                v-model="arr[i]"
                                controls-position="right"
                                style="width: 100%"
                                :step="0.1"
                                @change="changeArr"
                              />
                            </el-form-item>
                          </el-form>
                        </el-col>
                        <el-col :span="12">
                          <el-form label-width="20px" @submit.native.prevent>
                            <el-form-item label="Y:">
                              <el-input-number
                                v-model="srr[i]"
                                controls-position="right"
                                style="width: 100%"
                                :step="0.1"
                                @change="changeArr"
                              />
                            </el-form-item>
                          </el-form>
                        </el-col>
                      </el-row>
                    </el-form-item>
                  </span>
                  <el-form-item>
                    <el-button type="primary" @click="saveFenceEdit">{{
                      $t("operating.determine")
                    }}</el-button>
                    <el-button type="danger" @click="deleteForm">{{
                      oparts
                    }}</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-tab-pane> -->
          </el-tabs>
        </el-drawer>
        <el-dialog
          title="提示"
          :visible.sync="isOrder"
          width="30%"
          :before-close="handleClose"
        >
          <span>{{ msgText }}</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="isOrder = false">{{ $t("common.ccancel") }}</el-button>
            <el-button type="primary" @click="updateOrder">{{ $t("common.cok") }}</el-button>
          </span>
        </el-dialog>

      </el-tab-pane>

    </el-tabs>
  </div>
</template>

<script>
import workfence from './../components/workfence'
import { OSM, Vector as VectorSource } from 'ol/source'
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer'
import {
  Style,
  Icon,
  Text,
  Fill,
  Stroke,
  Circle as CircleStyle
} from 'ol/style'
import { getLength } from 'ol/sphere'
import { GeoJSON } from 'ol/format.js'
import { Draw, Modify, Snap, Select, Translate } from 'ol/interaction.js'
import { Circle, LineString, Point, Polygon } from 'ol/geom.js'
import { createRegularPolygon, createBox } from 'ol/interaction/Draw.js'
import { altKeyOnly, click, pointerMove } from 'ol/events/condition'
import { Image } from 'ol/layer.js'
import { ImageStatic } from 'ol/source.js'
import Overlay from 'ol/Overlay'
import { Projection } from 'ol/proj.js'

import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getMapTree, getMap } from '@/api/location'
import {
  fenceOneInfo,
  addFence,
  deleteFence
} from '@/api/system/historyDisplayInfo.js'
import i18n from '@/utils/lang/index'
import {
  sendThis,
  Load_Map,
  _iMap,
  _TransPixel,
  TagStyle,
  _Style,
  updateOverlayPosition,
  FenceStyle,
  _TransMetric,
  _TransMetric2,
  _TransMetric3,
  _TransMetricFence,
  _dPR,
  Load_Fence,
  FenceSource,
  Load_Fence2,
  FenceSource2

} from '@/utils/historyMapcy.js'
import {
  ccFenceAdd,
  ccFenceEdit,
  ccFenceDelete,
  ccFenceList,
  ccFenceAllList,
  ccFenceSave,
  ccFencQOrderNum,
  ccfenceModify,
  ccFenceId
} from '@/api/cy.js'
export default {
  components: { Treeselect, workfence }, // 注册树形穿梭框组件
  filters: {
    formatType(value) {
      if (value === '1') {
        return '作业流程'
      } else {
        return '路测流程'
      }
    }
  },
  data() {
    return {
      workFlowType: '',
      formArrList: [],
      optionList: [
        {
          value: 'all',
          label: '所有'
        },

        {
          value: '1',
          label: '作业流程'
        },
        {
          value: '2',
          label: '路测流程'
        }
      ],
      options: [
        {
          value: '1',
          label: '作业流程'
        },
        {
          value: '2',
          label: '路测流程'
        }
      ],
      activeName: 'second',
      mapId: null,
      mapList: [],
      disabled: false,
      arr: [],
      srr: [],
      colorFlag: 0,
      drawFormValue: 'None', // 绘制形状
      _Select: null,
      modify: null,
      draw: null,
      form: {
        fenceName: '',
        type: '1',
        fenceId: '',
        orderNum: '',
        maxDuration: '0',
        minDuration: '0',
        intoCount: '0',
        remark: '',
        operationId: '',
        operationName: ''
      },
      rules: {},

      coors: null,
      fenceEditVisible: false,
      fenceName: null,
      fenceType: null,
      mapName: null,
      Geo: null,
      delFenceVisible: false,
      sketchCoords: 6,
      measureTooltipElement2: null,
      measureTooltip2: null,
      value1: false,
      gratLayer: null,
      MeasureSource: null,
      MeasureLayer: null,
      oparts: '取消',
      count: 0,
      allDataCount: [],
      color1: null,
      color2: null,
      isOrder: null, // 是否排序文本弹窗
      msgText: null // 顺序修改后提示文字
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    updateOrder() {
      this.queryOrderNum()
    },
    handleClose() {
      this.isOrder = false
    },
    queryOrderNum() {
      ccfenceModify(this.form).then((res) => {
        if (res.code === 200) {
          this.isOrder = false
          setTimeout(() => {
            this.queryWorkFlow()
          }, 1500)
          this.msgSuccess(res.msg)
        }
      })
    },

    cancelflow() {
      this.fenceEditVisible = false
      this.formArrList = []
      this.resetForm('form')
    },
    fenceTempDel(row, index) {
      this.formArrList.splice(index, 1)
    },
    // handleChangeNum() {
    //   ccFencQOrderNum(this.form).then(res => {

    //     return
    //     if (res.code === 400) {
    //       this.msgText = res.msg
    //       this.isOrder = true
    //     } else if (res.code === 200) {

    //     }
    //   })
    // },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          ccFencQOrderNum(this.form).then(res => {
            if (res.code === 400) {
              this.msgText = res.msg
              this.isOrder = true
            } else if (res.code === 200) {
              this.isOrder = false
            }
          })
          // const formObj = JSON.parse(JSON.stringify(this.form))
          // this.formArrList.push(formObj)
          // this.resetForm('form')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    saveTempFence() {
      ccFenceAdd(this.formArrList).then((res) => {
        if (res.code === 200) {
          this.msgSuccess(res.msg)
          this.fenceEditVisible = false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    handleClick(tab, event) {
      console.log(tab.name, tab.name === 'second', tab, event)
      this.fenceEditVisible = false
      if (tab.name === 'second') {
        //  this.$refs.mychild.handleEdit(index, row)
        this.$refs.workFlow.initData()
      } else {
        this.nodeClick()
      }
    },
    init() {
      // 加载地图树
      getMapTree().then((res) => {
        const RES = this.responseUse(res)
        console.log(res, RES)
        if (typeof RES !== 'undefined') {
          this.mapList = RES
          sendThis(this)
          this.mapId = RES[0].id
          // this.nodeClick()
        }
      })
    },

    nodeClick() {
      const self = this
      console.log(self.mapId)
      if (self.mapId === '' || self.mapId === undefined) {
        return
      }
      getMap(self.mapId).then((res) => {
        const RES = self.responseUse(res)
        if (RES != undefined) {
          $('#map').empty()
          self.mapName = RES.mapName
          Load_Map(
            '/file' + RES.mapPath,
            RES.mapActualX,
            RES.mapActualY,
            RES.mapPixelX,
            RES.mapPixelY,
            RES.mapPixelX / RES.mapActualX,
            [RES.mapOriginX, RES.mapOriginY]
          )
          Load_Fence(self.mapId, 'all')
          Load_Fence2()
          self.fenceModify_init()
          self.createMeasureTooltip2()
        }
      })
    },
    queryWorkFlow() {
      this.fenceEditVisible = false
      if (this.workFlowType == 'all') {
        Load_Fence(this.mapId, 'all')
      } else {
        Load_Fence(this.mapId, this.workFlowType)
      }
    },

    handleChange(val, type) {
      this.colorFlag = val
      this.drawFormValue = type
      this.arr = []
      this.srr = []
      this.fenceModify_init()
    },
    // 修改围栏开始
    fenceModify_init() {
      const self = this
      if (self._Select != null) {
        _iMap.removeInteraction(self._Select)
      }
      if (self.modify != null) {
        _iMap.removeInteraction(self.modify)
      }
      if (self.draw != null) {
        _iMap.removeInteraction(self.draw)
      }
      if (self.drawFormValue == 'None') {
        self._Select = null
      } else if (self.drawFormValue == 'Box') {
        self.draw = new Draw({
          source: FenceSource2,
          type: 'Circle',
          geometryFunction: createBox()
        })
      } else if (self.drawFormValue == 'Square') {
        self.draw = new Draw({
          source: FenceSource2,
          type: 'Circle',
          geometryFunction: createRegularPolygon(4)
        })
      } else if (self.drawFormValue == 'Circle') {
        self.draw = new Draw({
          source: FenceSource,
          type: 'Circle'
        })
      } else if (self.drawFormValue == 'Polygon') {
        self.draw = new Draw({
          source: FenceSource2,
          type: 'Polygon'
        })
      } else if (self.drawFormValue == 'Select') {
        self._Select = new Select({
          condition: click
        })
      } else if (self.drawFormValue == 'BiaoChi') {
        self.draw = new Draw({
          source: FenceSource2,
          type: 'LineString'
        })
      }
      if (self.drawFormValue == 'Select') {
        _iMap.addInteraction(self._Select)
        self.modify = new Modify({
          features: self._Select.getFeatures()
        })
        _iMap.addInteraction(self.modify)

        // 选中围栏
        self._Select.on('select', function(e) {
          if (e.selected.length > 0) {
            if (e.selected[0].get('geometry').getType() == 'Circle') {
              return
            }
            e.selected.forEach(function(f) {
              self.fenceId = f.get('id')
              if (self.fenceId == undefined) {
                self.fenceName = null
                self.fenceType = null
                return
              }
              for (var k = 0; k < self.count; k++) {
                _iMap.removeOverlay(_iMap.getOverlayById(k))
              }
              self.count = f.get('geometry').getCoordinates()[0].length - 1
              self.allDataCount = f.get('geometry').getCoordinates()
              self.allDataCount = _TransMetric3(self.allDataCount, 2)
              for (var j = 0; j < self.allDataCount.length; j++) {
                self.allDataCount[j] = self.allDataCount[j].map(Number)
              }
              self.allDataCount.pop()
              self.arr = []
              self.srr = []
              self.allDataCount.forEach((element, index) => {
                self.arr[index] = element[0]
                self.srr[index] = element[1]
              })

              f.get('geometry')
                .getCoordinates()[0]
                .forEach(function(e, i) {
                  if (self.count == i) {
                    return
                  }
                  var measureTooltipElement = document.createElement('div')
                  measureTooltipElement.className = 'ol-circle'
                  var measureTooltip = new Overlay({
                    id: i,
                    element: measureTooltipElement,
                    offset: [0, -5],
                    positioning: 'bottom-center'
                  })
                  _iMap.addOverlay(measureTooltip)
                  measureTooltipElement.innerHTML = i
                  measureTooltip.setPosition(e)
                })

              if (f.get('operationId')) {
                self.form.operationId = f.get('operationId')
                self.form.operationName = f.get('operationName')
                self.form.orderNum = f.get('orderNum')
                self.form.type = (f.get('type')).toString()
                ccFenceId(self.form.operationId).then(res => {
                  if (res.code === 200) {
                    self.fenceEditVisible = true
                    self.form.maxDuration = res.data.maxDuration
                    self.form.minDuration = res.data.minDuration
                    self.form.intoCount = res.data.intoCount
                    self.form.remark = res.data.remark
                    self.form.fenceId = res.data.fenceId
                    self.form.fenceName = res.data.fenceName
                  }
                })
              } else {
                self.fenceEditVisible = false
                self.msgError('该流程未添加，请先添加流程')
              }

              // fenceOneInfo(self.fenceId).then((res) => {
              //   console.log('选中围栏的数据', res)
              //   const RES = self.responseUse(res)
              //   if (RES != undefined) {
              //     //   self.fenceEditVisible = true
              //     self.fenceName = RES.fenceName
              //     self.fenceType = RES.fenceType.split(',')
              //     self.coors = RES.posGroup

              //     self.form.fenceId = RES.idx
              //     self.form.fenceName = RES.fenceName
              //     self.formArrList = []
              //   }
              // })
            })
          }
        })

        self.modify.on('modifyend', function(e) {
          const f = e.features.array_[0]
          for (var k = 0; k < self.count; k++) {
            _iMap.removeOverlay(_iMap.getOverlayById(k))
          }
          self.count = f.get('geometry').getCoordinates()[0].length - 1
          self.allDataCount = f.get('geometry').getCoordinates()
          self.allDataCount = _TransMetric3(self.allDataCount, 2)
          for (var j = 0; j < self.allDataCount.length; j++) {
            self.allDataCount[j] = self.allDataCount[j].map(Number)
          }
          self.allDataCount.pop()
          self.arr = []
          self.srr = []
          self.allDataCount.forEach((element, index) => {
            self.arr[index] = element[0]
            self.srr[index] = element[1]
          })
          f.get('geometry')
            .getCoordinates()[0]
            .forEach(function(e, i) {
              if (self.count == i) {
                return
              }
              var measureTooltipElement = document.createElement('div')
              measureTooltipElement.className = 'ol-circle'
              var measureTooltip = new Overlay({
                id: i,
                element: measureTooltipElement,
                offset: [0, -3],
                positioning: 'bottom-center'
              })
              _iMap.addOverlay(measureTooltip)
              measureTooltipElement.innerHTML = i
              measureTooltip.setPosition(e)
            })
        })
        self.oparts = i18n.t('operating.delete')
      } else if (
        self.drawFormValue == 'Box' ||
        self.drawFormValue == 'Square'
      ) {
        _iMap.addInteraction(self.draw)
        self.draw.on('drawstart', function(sketch) {
          if (self.fenceId == 'temporary') {
            self
              .$confirm(
                i18n.t('operating.drawRect'),
                i18n.t('operating.prompt'),
                {
                  confirmButtonText: i18n.t('common.cok'),
                  cancelButtonText: i18n.t('operating.cancel'),
                  type: 'warning'
                }
              )
              .then(() => {
                FenceSource2.removeFeature(
                  FenceSource2.getFeatureById(self.fenceId)
                )
                for (var k = 0; k < self.count; k++) {
                  _iMap.removeOverlay(_iMap.getOverlayById(k))
                }
              })
              .catch(() => {
                self.draw.abortDrawing()
              })
          }
          sketch.feature.getGeometry().on('change', function(evt) {
            var tooltipCoord = evt.target.getInteriorPoint().getCoordinates()
            self.measureTooltip2.setPosition(tooltipCoord)
            var geom = evt.target.extent_
            var height = ((geom[3] - geom[1]) / _dPR).toFixed(2)
            var width = ((geom[2] - geom[0]) / _dPR).toFixed(2)
            var output = 'width:' + width + 'm  height:' + height + 'm'
            self.measureTooltipElement2.innerHTML = output
          })
        })
        self.draw.on('drawend', function(evt) {
          self.drawingEnd(evt)
          // self.measureTooltip2.setPosition(undefined);
        })
        self.oparts = i18n.t('operating.cancel')
      } else if (self.drawFormValue == 'Circle') {
        _iMap.addInteraction(self.draw)
        self.draw.on('drawstart', function(sketch) {
          sketch.feature.getGeometry().on('change', function(evt) {
            var centerLogLat = [
              (evt.target.extent_[0] + evt.target.extent_[2]) / 2,
              (evt.target.extent_[1] + evt.target.extent_[3]) / 2
            ]
            var radius = (evt.target.extent_[2] - evt.target.extent_[0]) / 2
            self.measureTooltip2.setPosition(centerLogLat)
            var output = 'radius:' + (radius / _dPR).toFixed(2) + 'm'
            self.measureTooltipElement2.innerHTML = output
          })
        })
        self.draw.on('drawend', function(evt) {
          self.drawCircleEnd(evt)
          self.measureTooltip2.setPosition(undefined)
        })
        self.oparts = i18n.t('operating.cancel')
      } else if (self.drawFormValue == 'Polygon') {
        _iMap.addInteraction(self.draw)
        self.draw.on('drawstart', function(sketch) {
          if (self.fenceId == 'temporary') {
            FenceSource2.removeFeature(
              FenceSource2.getFeatureById(self.fenceId)
            )
          }
          for (var k = 0; k < self.count; k++) {
            _iMap.removeOverlay(_iMap.getOverlayById(k))
          }
          sketch.feature.getGeometry().on('change', function(evt) {
            var tooltipCoord = evt.target.getInteriorPoint().getCoordinates()
            self.measureTooltip2.setPosition(tooltipCoord)
            var geom = evt.target.extent_
            var height = ((geom[3] - geom[1]) / _dPR).toFixed(2)
            var width = ((geom[2] - geom[0]) / _dPR).toFixed(2)
            var output = 'width:' + width + 'm  height:' + height + 'm'
            self.measureTooltipElement2.innerHTML = output
          })
        })

        self.draw.on('drawend', function(evt) {
          self.drawingEnd(evt)
        })
        self.oparts = i18n.t('operating.cancel')
      } else if (self.drawFormValue == 'BiaoChi') {
        _iMap.addInteraction(self.draw)
        self.draw.on('drawstart', function(sketch) {
          var measureTooltipElement = document.createElement('div')
          measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure'
          var measureTooltip = new Overlay({
            element: measureTooltipElement,
            offset: [0, -15],
            positioning: 'bottom-center'
          })
          _iMap.addOverlay(measureTooltip)
          sketch.feature.getGeometry().on('change', function(evt) {
            var geom = evt.target
            var output
            var tooltipCoord
            if (geom instanceof LineString) {
              output = self.formatLength(geom)
              tooltipCoord = geom.getLastCoordinate()
            }
            measureTooltipElement.innerHTML = output
            measureTooltip.setPosition(tooltipCoord)
          })
        })
      }
    },
    createMeasureTooltip2() {
      if (this.measureTooltipElement2) {
        this.measureTooltipElement2.parentNode.removeChild(
          this.measureTooltipElement2
        )
      }
      this.measureTooltipElement2 = document.createElement('div')
      this.measureTooltipElement2.className = 'ol-tooltip ol-tooltip-measure'
      this.measureTooltip2 = new Overlay({
        element: this.measureTooltipElement2,
        offset: [0, -15],
        positioning: 'bottom-center'
      })
      _iMap.addOverlay(this.measureTooltip2)
    },
    closeDialog() {
      const self = this
      self.measureTooltip2.setPosition(undefined)
      Load_Fence2()
      if (self.modify != null) {
        _iMap.removeInteraction(self.modify)
      }
      if (self.drawFormValue == 'Select') {
        const _selectedFeatures = self._Select.getFeatures()
        _selectedFeatures.clear()
        // Load_Fence(self.mapId)
        Load_Fence(self.mapId, self.workFlowType)
        self.fenceModify_init()
      } else {
        // Load_Fence(self.mapId)
        Load_Fence(self.mapId, self.workFlowType)
        self.fenceModify_init()
      }
      for (var k = 0; k < self.count; k++) {
        _iMap.removeOverlay(_iMap.getOverlayById(k))
      }
      self.fenceEditVisible = false
      self.fenceName = null
      self.fenceType = null
      self.coors = null
      self.fenceId = null
      self.disabled = false
      self.formArrList = []
      self.resetForm('form')
    },
    // 提交围栏类型转换
    drawingEnd(evt) {
      const self = this
      const geo = evt.feature.getGeometry()
      const type = geo.getType()
      let coors
      if (type == 'Polygon') {
        coors = geo.getCoordinates()
        self.coors = '[' + _TransMetric2(coors, 2).toString() + ']'
        self.fenceEditVisible = true
      }
      evt.feature.setId('temporary')
      self.fenceId = 'temporary'

      const coordinates = geo.getCoordinates()
      self.count = coordinates[0].length - 1
      self.allDataCount = coordinates
      self.allDataCount = _TransMetric3(self.allDataCount, 2)
      for (var j = 0; j < self.allDataCount.length; j++) {
        self.allDataCount[j] = self.allDataCount[j].map(Number)
      }
      self.allDataCount.pop()
      self.arr = []
      self.srr = []
      self.allDataCount.forEach((element, index) => {
        self.arr[index] = element[0]
        self.srr[index] = element[1]
      })
      geo.getCoordinates()[0].forEach(function(e, i) {
        if (self.count == i) {
          return
        }
        var measureTooltipElement = document.createElement('div')
        measureTooltipElement.className = 'ol-circle'
        var measureTooltip = new Overlay({
          id: i,
          element: measureTooltipElement,
          offset: [0, -3],
          positioning: 'bottom-center'
        })
        _iMap.addOverlay(measureTooltip)
        measureTooltipElement.innerHTML = i
        measureTooltip.setPosition(e)
      })
      self.modify = new Modify({
        source: FenceSource2
      })
      _iMap.addInteraction(self.modify)

      self.modify.on('modifyend', function(e) {
        const f = e.features.array_[0]
        for (var k = 0; k < self.count; k++) {
          _iMap.removeOverlay(_iMap.getOverlayById(k))
        }
        self.count = f.get('geometry').getCoordinates()[0].length - 1
        self.allDataCount = f.get('geometry').getCoordinates()
        self.allDataCount = _TransMetric3(self.allDataCount, 2)
        for (var j = 0; j < self.allDataCount.length; j++) {
          self.allDataCount[j] = self.allDataCount[j].map(Number)
        }
        self.allDataCount.pop()
        self.arr = []
        self.srr = []
        self.allDataCount.forEach((element, index) => {
          self.arr[index] = element[0]
          self.srr[index] = element[1]
        })
        f.get('geometry')
          .getCoordinates()[0]
          .forEach(function(e, i) {
            if (self.count == i) {
              return
            }
            var measureTooltipElement = document.createElement('div')
            measureTooltipElement.className = 'ol-circle'
            var measureTooltip = new Overlay({
              id: i,
              element: measureTooltipElement,
              offset: [0, -3],
              positioning: 'bottom-center'
            })
            _iMap.addOverlay(measureTooltip)
            measureTooltipElement.innerHTML = i
            measureTooltip.setPosition(e)
          })
      })
    },
    changeArr() {
      var collectPoint = []
      var cachePoint = []
      var pixelPosition
      this.arr.forEach((element, index) => {
        collectPoint.push([element, this.srr[index]])
      })
      cachePoint.push(collectPoint)
      cachePoint[0].push(collectPoint[0])

      pixelPosition = _TransPixel(cachePoint)
      let currentFeature
      if (this.fenceId == 'temporary') {
        currentFeature = FenceSource2.getFeatureById(this.fenceId)
      } else {
        currentFeature = FenceSource.getFeatureById(this.fenceId)
      }
      currentFeature.getGeometry().setCoordinates(pixelPosition)
      pixelPosition[0].pop()
      pixelPosition[0].forEach((element, index) => {
        var currentOverLayer = _iMap.getOverlayById(index)
        currentOverLayer.setPosition(element)
      })
    },
    // 绘制圆形围栏结束
    drawCircleEnd(evt) {
      var centerLogLat, radius
      var circle = evt.feature.getGeometry()
      centerLogLat = circle.getCenter()
      radius = circle.getRadius()
      this.coors = '[' + _TransMetric2(centerLogLat, 2).toString() + ']'
      console.log(this.coors, (radius / _dPR).toFixed(2))
    },
    saveFenceEdit() {
      const self = this
      if (
        self.fenceId == null ||
        self.fenceId == '' ||
        self.fenceId == undefined
      ) {
        const param = {
          fenceName: self.fenceName,
          fenceType: self.fenceType.join(','),
          layerId: self.mapId,
          layerName: self.mapName,
          posGroupArray: eval(self.coors)
        }
        addFence(param).then((res) => {
          const RES = self.responseUse(res, true)
          if (RES) {
            self.fenceEditVisible = false
            self.fenceName = null
            self.fenceType = null
            self.coors = null
            // Load_Fence(self.mapId)
            Load_Fence(self.mapId, self.workFlowType)
          }
        })
      } else if (self.fenceId == 'temporary') {
        var currentPoint = []
        self.arr.forEach((element, index) => {
          currentPoint.push([element, self.srr[index]])
        })
        currentPoint.push(currentPoint[0])
        self.coors = eval(currentPoint)
        const param = {
          fenceName: self.fenceName,
          fenceType: self.fenceType.join(','),
          layerId: self.mapId,
          layerName: self.mapName,
          posGroupArray: self.coors
        }
        addFence(param).then((res) => {
          const RES = self.responseUse(res, true)
          if (RES) {
            self.fenceEditVisible = false
            self.fenceName = null
            self.fenceType = null
            self.coors = null
            self.fenceId = null
            // Load_Fence(self.mapId)
            Load_Fence(self.mapId, self.workFlowType)
          }
        })
      } else {
        var currentPoint = []
        self.arr.forEach((element, index) => {
          currentPoint.push([element, self.srr[index]])
        })
        currentPoint.push(currentPoint[0])
        self.coors = eval(currentPoint)
        const param = {
          fenceName: self.fenceName,
          fenceType: self.fenceType.join(','),
          layerId: self.mapId,
          layerName: self.mapName,
          posGroupArray: self.coors,
          idx: this.fenceId
        }
        addFence(param).then((res) => {
          const RES = self.responseUse(res, true)
          if (RES) {
            self.fenceEditVisible = false
            self.fenceName = null
            self.fenceType = null
            self.coors = null
            self.fenceId = null
            // Load_Fence(self.mapId)
            Load_Fence(self.mapId, self.workFlowType)
          }
        })
      }
    },
    deleteForm() {
      if (this.oparts == i18n.t('operating.cancel')) {
        this.fenceEditVisible = false
      } else if (this.oparts == i18n.t('operating.delete')) {
        this.delFenceVisible = true
      }
    },
    deleteFence() {
      const param = {
        idx: this.fenceId
      }
      deleteFence([param]).then((res) => {
        const RES = this.responseUse(res, true)
        if (RES) {
          const currentFeature = FenceSource.getFeatureById(this.fenceId)
          FenceSource.removeFeature(currentFeature)
          this.delFenceVisible = false
          this.fenceEditVisible = false
        }
      })
    },
    pointerMoveHandler(evt) {
      if (evt.dragging) {
        return
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.map-container {
  width: 100%;
  height: calc(100% - 100px);
  // border: 1px solid red;
}
div#map {
  // border: 1px solid #1fcd5a;
  height: 100%;
}
::v-deep .el-tabs.el-tabs--top {
  height: calc(100% - 40px);
  width: 95% !important;
}
::v-deep .el-tab-pane {
  height: 100%;
  box-sizing: border-box;
  overflow: hidden;
  overflow-y: auto;
}
::v-deep .el-tabs__content {
  height: 100%;
}
::v-deep .el-drawer__wrapper {
  //width: 480px;
  width: 640px;
  left: unset;
  border-left: 1px solid #dcd7d7;
}
::v-deep .el-dialog {
  min-width: 640px;
}
.el-drawer.rtl.changeDialog {
  padding: 0px 10px;
}
.el-col.el-col-1\.5 {
  display: flex;
  align-items: center;
}
</style>
